package com.luo.bbs.front.webapi.controller;

import com.luo.common.restful.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/img")
public class ImgLoadController {
    @Value("${bbs-front.resource.path}")
    private File resourcePath;
    @Value("${bbs-front.resource.host}")
    private String resourceHost;

    @PostMapping("/post")
    public JsonResult imgLoad(MultipartFile file) throws IOException {
        //获得文件名
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID() + ext;

        //创建一个文件夹，按日期存储图片
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormat = format.format(date);

//       String path = resourcePath+"/"+dateFormat;
//       new File(path);
        File folder = new File(resourcePath,dateFormat);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File imgFile = new File(folder,name);
        file.transferTo(imgFile);
        //FileUtils.copyInputStreamToFile(file.getInputStream(), imgFile);

        String url = resourceHost + "/" + dateFormat + "/" + name;
        log.debug(imgFile.getAbsolutePath()+"绝对路径");
        log.debug(url);
        return JsonResult.ok(url);
    }
}
